package com.ideabove.radio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.ideabove.data.PushedData;
import com.ideabove.radio.R;
import com.ideabove.util.UniqueDeviceID;

public class GCMIntentService extends GCMBaseIntentService {
	private static final String tag = "GCMIntentService";
	public static final String SEND_ID = "AIzaSyC-DhGzYM4-xS__ki5KWO-Jf2pApW8jNoY";
	private static final int HELLO_ID = 378298;
	
	public GCMIntentService(){ this(SEND_ID); }
	
	public GCMIntentService(String senderId) { super(senderId); }

	@Override
	protected void onMessage(Context context, Intent intent) {
		Bundle b = intent.getExtras();

		Iterator<String> iterator = b.keySet().iterator();
		
		PushedData pData = new PushedData();
		
		while(iterator.hasNext()) {
			String key = iterator.next();
			String value = b.get(key).toString();
			Log.e(tag, "onMessage. "+key+" : "+value);

			if("title".equals(key)){
				pData.setTitle(value);
			}else if("type".equals(key)){
				pData.setType(value);
			}else if("value".equals(key)){
				pData.setValue(value);
			}
		}
		
		showMessageOnStatusBar(context, pData);		
		
	}

	@Override
	protected void onError(Context context, String errorId) {
		Log.d(tag, "onError. errorId : "+errorId);
	}

	@Override
	protected void onRegistered(Context context, String regId) {
		Log.e(tag, "onRegistered. regId : "+regId);
		requestRegDeviceId(regId);
	}

	@Override
	protected void onUnregistered(Context context, String regId) {
		Log.d(tag, "onUnregistered. regId : "+regId);
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		Log.d(tag, "onRecoverableError. errorId : "+errorId);
		return super.onRecoverableError(context, errorId);
	}
	
	
	private void showMessageOnStatusBar(Context context, PushedData pdata){
		
		try{
		String title = pdata.getTitle();
		String type = pdata.getType();
		String value = pdata.getValue();
				
//		if(Integer.parseInt(type) != 0){
		
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
			int icon = R.drawable.nofify_25;
			CharSequence tickerText = title;
			long when = System.currentTimeMillis();
	
			CharSequence contentTitle = title;
			CharSequence contentText = value;
			
	//		Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
	//		Uri u = Uri.parse(value);
	//		notificationIntent.setData(u); 
					
			// the next two lines initialize the Notification, using the configurations above
			Notification notification = new Notification(icon, tickerText, when);
			notification.defaults |= Notification.DEFAULT_SOUND;
			notification.defaults |= Notification.DEFAULT_VIBRATE; 	
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			
			Intent notificationIntent = new Intent(this, PushedActivity.class);			
			notificationIntent.putExtra("pushedData", pdata);			
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);		
			mNotificationManager.notify(HELLO_ID, notification);
			
			
//			Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(value));
//		    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
//		    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
//		    mNotificationManager.notify(970970, notification);
//		}
		}catch(Exception e){
			e.printStackTrace();
		}
		

	}
	
	
	public void requestRegDeviceId(String regId) {
        try {
             
             URL url = new URL("http://s.bonosound.com/radio_android_push/login_android.php");       	
             HttpURLConnection http = (HttpURLConnection) url.openConnection(); 			
             
             http.setDefaultUseCaches(false);                                           
             http.setDoInput(true);            
             http.setDoOutput(true);            
             http.setRequestMethod("POST");    

             http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
             String deviceUniqueId = UniqueDeviceID.getUniqueDeivceID(getBaseContext());
             StringBuffer buffer = new StringBuffer();
             buffer.append("q").append("=").append("ndev").append("&");         
             buffer.append("reg_id").append("=").append(regId).append("&");
             buffer.append("device_id").append("=").append(deviceUniqueId);
           
             OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
             PrintWriter writer = new PrintWriter(outStream);
             writer.write(buffer.toString());
             writer.flush();

             InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8"); 
             BufferedReader reader = new BufferedReader(tmp);
             StringBuilder builder = new StringBuilder();
             String str;
             while ((str = reader.readLine()) != null) {       		
                  builder.append(str + "\n");                     	
             }
             
             
             String myResult = builder.toString();                  
             Log.e(tag, "HTTP RESULT : "+myResult);
             
             reader.close();
             tmp.close();
             
        } catch (MalformedURLException e) {
        	Log.e(tag, "HTTP RESULT : "+e.getMessage());
        } catch (IOException e) {
        	Log.e(tag, "HTTP RESULT : "+e.getMessage());
        }
   }
}